package com.jy.appmarket.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.jy.appmarket.R;
import com.jy.appmarket.adapter.ApkFileManagerSectiondAdapter;
import com.jy.appmarket.adapter.ApkFileManagerSectiondAdapter.ApkFileManagerSectionClickCallBack;
import com.jy.appmarket.adapter.ApkFileManagerSectiondAdapter.ApkFileUiSection;
import com.jy.appmarket.cards.ApkFileUICard;
import com.jy.appmarket.cards.ApkFileUICard.ApkFileUICheckBoxClickCallBack;
import com.jy.appmarket.dialog.TextDialog;
import com.jy.appmarket.model.ApkFileInfo;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.view.LoadingView;
import com.jy.appmarket.view.LoadingView.OnClickListener;

import android.app.ActionBar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.Formatter;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;

public class ApkFileManagerActivity extends Activity
		implements ApkFileUICheckBoxClickCallBack, ApkFileManagerSectionClickCallBack {

	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private ApkFileManagerSectiondAdapter mSectionAdapter;
	private ArrayList<ApkFileUiSection> mSectionArray = new ArrayList<ApkFileUiSection>();
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();

	private LoadingView mLoadingView;
	private List<ApkFileInfo> mRecommendHoldList = new ArrayList<ApkFileInfo>();
	private List<ApkFileInfo> mRecommendClearList = new ArrayList<ApkFileInfo>();
	private View mContentLayout;
	private Button mClearBtn;
	private long mClearFileSize;
	private TextDialog mDeleteConfimDialog = null;
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent == null || !intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
				return;
			}
			String packageName = intent.getDataString();
			if (packageName != null && packageName.length() > 0) {
				packageName = packageName.substring(packageName.lastIndexOf(':') + 1);
				for (int i = 0; i < mRecommendHoldList.size(); i++) {
					if (packageName.equals(mRecommendHoldList.get(i).getPackName())) {
						int versionCode = PackageUtils.getVersionCode(getApplicationContext(), packageName);
						if (versionCode == mRecommendHoldList.get(i).getFileVersionCode()) {
							File file = new File(mRecommendHoldList.get(i).getFilePath());
							if (file.exists()) {
								ApkFileInfo temp = mRecommendHoldList.get(i);
								temp.setType(1);
								temp.setDescription("已安装相同版本");
								temp.setSelect(false);
								mRecommendClearList.add(temp);
							}
							mRecommendHoldList.remove(i);
							setupUI();
							break;
						}
					}
				}
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_apk_file_manager);

		initTitle();
		initViews();
		loadData();
		registerPackageInstallBroadcast();
	}

	private void registerPackageInstallBroadcast() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
		filter.addDataScheme("package");
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		registerReceiver(mReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("安装包管理");
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void initViews() {
		mLoadingView = findViewById(R.id.apk_file_manager_loading_view);
		mLoadingView.setOnClickListener(new OnClickListener() {

			@Override
			public void onLoadingViewClick(View view) {
				loadData();
			}
		});
		mLoadingView.showWaitView("正在查找本地安装包文件");
		mLoadingView.setVisibility(View.VISIBLE);

		mContentLayout = findViewById(R.id.apk_file_manager_content_layout);
		mContentLayout.setVisibility(View.GONE);
		mListview = findViewById(R.id.apk_flie_manager_listview);
		mListview.needToRefreshOnFooter(false);
		mListview.needToRefreshOnHeader(false);
		mClearBtn = findViewById(R.id.apk_file_manager_clear_btn);
		mClearBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				clearFile();
			}
		});
	}

	private void clearFile() {
		mClearFileSize = 0;
		for (int i = 0; i < mRecommendClearList.size();) {
			if (mRecommendClearList.get(i).getSelect()) {
				File file = new File(mRecommendClearList.get(i).getFilePath());
				if (file.exists()) {
					boolean ret = file.delete();
					if (ret) {
						// Toast.makeText(this, "文件" +
						// mRecommendClearList.get(i).getFileName() + "删除成功",
						// Toast.LENGTH_SHORT).show();
						mClearFileSize += mRecommendClearList.get(i).getFileSize();
						mRecommendClearList.remove(i);
						continue;
					} else {
						Toast.makeText(this, "文件" + mRecommendClearList.get(i).getFileName() + "删除失败",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
			i++;
		}

		for (int i = 0; i < mRecommendHoldList.size();) {
			if (mRecommendHoldList.get(i).getSelect()) {
				File file = new File(mRecommendHoldList.get(i).getFilePath());
				if (file.exists()) {
					boolean ret = file.delete();
					if (ret) {
						// Toast.makeText(this, "文件" +
						// mRecommendHoldList.get(i).getFileName() + "删除成功",
						// Toast.LENGTH_SHORT).show();
						mClearFileSize += mRecommendHoldList.get(i).getFileSize();
						mRecommendHoldList.remove(i);
						continue;
					} else {
						Toast.makeText(this, "文件" + mRecommendHoldList.get(i).getFileName() + "删除失败",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
			i++;
		}
		Toast.makeText(this, "清理完成，为您节省 " + Formatter.formatFileSize(this, mClearFileSize), Toast.LENGTH_SHORT).show();
		setupUI();
		// mCardsAdapter.notifyDataSetChanged();
	}

	private void loadData() {
		mRecommendClearList.clear();
		mRecommendHoldList.clear();

		new Thread(new Runnable() {
			@Override
			public void run() {
				findAllApkFile(Environment.getExternalStorageDirectory());
				ApkFileManagerActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						setupUI();
					}
				});
			}
		}).start();
	}

	private void setupUI() {

		if (mRecommendClearList.size() == 0 && mRecommendHoldList.size() == 0) {
			mLoadingView.setVisibility(View.VISIBLE);
			mContentLayout.setVisibility(View.GONE);
			if (mClearFileSize == 0) {
				mLoadingView.showEmptyView("没有安装包", R.drawable.apk_file_empty);
			} else {
				mLoadingView.showEmptyView("清理完成，为您节省" + Formatter.formatFileSize(this, mClearFileSize) + "!",
						R.drawable.apk_file_clear_success);
			}
		} else {
			mCardsArray.clear();
			mSectionArray.clear();
			for (int i = 0; i < mRecommendClearList.size(); i++) {
				ApkFileUICard fileUICard = new ApkFileUICard(this, mRecommendClearList.get(i), this);
				mCardsArray.add(fileUICard);
			}
			for (int j = 0; j < mRecommendHoldList.size(); j++) {
				ApkFileUICard fileUICard = new ApkFileUICard(this, mRecommendHoldList.get(j), this);
				mCardsArray.add(fileUICard);
			}

			if (mRecommendClearList.size() > 0) {
				long fileSize = 0;
				int i;
				boolean sectionSelectFlag = true;
				for (i = 0; i < mRecommendClearList.size(); i++) {
					fileSize += mRecommendClearList.get(i).getFileSize();
					if (!mRecommendClearList.get(i).getSelect()) {
						sectionSelectFlag = false;
					}
				}
				mSectionArray.add(new ApkFileUiSection(0,
						"建议清理(" + i + "个,占" + Formatter.formatFileSize(this, fileSize) + ")", sectionSelectFlag, 0));
			}
			if (mRecommendHoldList.size() > 0) {
				long fileSize = 0;
				int i;
				boolean sectionSelectFlag = true;
				for (i = 0; i < mRecommendHoldList.size(); i++) {
					fileSize += mRecommendHoldList.get(i).getFileSize();
					if (!mRecommendHoldList.get(i).getSelect()) {
						sectionSelectFlag = false;
					}
				}
				mSectionArray.add(new ApkFileUiSection(mRecommendClearList.size(),
						"建议保留(" + i + "个,占" + Formatter.formatFileSize(this, fileSize) + ")", sectionSelectFlag, 1));
			}

			if (mListview.getAdapter() == null) {
				mCardsAdapter = new CardArrayAdapter(this, mCardsArray);
				mCardsAdapter.setInnerViewTypeCount(500);
				mSectionAdapter = new ApkFileManagerSectiondAdapter(this, mCardsAdapter, this);
				mListview.setExternalAdapter(mSectionAdapter, mCardsAdapter);
			}

			ApkFileUiSection[] dummy = new ApkFileUiSection[mSectionArray.size()];

			// Sectioned adapter
			mSectionAdapter.setCardSections(mSectionArray.toArray(dummy));
			mCardsAdapter.notifyDataSetChanged();
			mSectionAdapter.notifyDataSetChanged();

			mLoadingView.setVisibility(View.GONE);
			mContentLayout.setVisibility(View.VISIBLE);
			updateClearButton();
		}
	}

	private void findAllApkFile(File file) {

		if (file.isFile()) {
			if (!file.canWrite()) {
				return;
			}
			String fileName = file.getName();
			if (fileName.toLowerCase().endsWith(".apk")) {
				ApkFileInfo apkFile = new ApkFileInfo();
				String apk_path = null;
				apk_path = file.getAbsolutePath();// apk文件的绝对路劲

				PackageManager pm = this.getPackageManager();
				PackageInfo packageInfo = pm.getPackageArchiveInfo(apk_path, PackageManager.GET_ACTIVITIES);
				if (packageInfo == null) {
					return;
				}
				ApplicationInfo appInfo = packageInfo.applicationInfo;

				if (appInfo == null) {
					return;
				}
				/** 获取apk的图标 */
				appInfo.sourceDir = apk_path;
				appInfo.publicSourceDir = apk_path;

				Drawable apk_icon = appInfo.loadIcon(pm);
				// Drawable apk_icon = getApkIcon(this,apk_path);
				if (apk_icon != null) {
					apkFile.setFileIcon(apk_icon);
				}
				/** 得到包名 */
				apkFile.setPackName(packageInfo.packageName);
				/** apk的绝对路劲 */
				apkFile.setFilePath(file.getAbsolutePath());
				/** apk的版本名称 String */
				apkFile.setFileVersionName(packageInfo.versionName);
				apkFile.setFileVersionCode(packageInfo.versionCode);

				apkFile.setType(doType(pm, packageInfo.packageName, packageInfo.versionCode));
				apkFile.setFileName(appInfo.loadLabel(pm).toString());
				apkFile.setFileSize(file.length());
				apkFile.setId(file.hashCode());

				if (apkFile.getType() == 0) {
					apkFile.setDescription("已安装更高版本");
					mRecommendClearList.add(apkFile);
				} else if (apkFile.getType() == 1) {
					apkFile.setDescription("已安装相同版本");
					mRecommendClearList.add(apkFile);
				} else if (apkFile.getType() == 10) {
					apkFile.setDescription("新版本安装包");
					mRecommendHoldList.add(apkFile);
				} else {
					apkFile.setDescription("最近下载但未安装");
					mRecommendHoldList.add(apkFile);
				}
			}

		} else {
			File[] files = file.listFiles();
			if (files != null && files.length > 0) {
				for (File file_str : files) {
					findAllApkFile(file_str);
				}
			}
		}
	}

	private int doType(PackageManager pm, String packageName, int versionCode) {
		List<PackageInfo> pakageinfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
		for (PackageInfo pi : pakageinfos) {
			String pi_packageName = pi.packageName;
			int pi_versionCode = pi.versionCode;
			// 如果这个包名在系统已经安装过的应用中存在
			if (packageName.equals(pi_packageName)) {
				// Log.i("test","此应用安装过了");
				if (versionCode <= pi_versionCode) {
					if (versionCode < pi_versionCode) {// 建议删除
						return 0;
					} else {
						return 1;
					}
				} else {
					return 10; // 建议保留
				}
			}
		}
		return 11; // 未安装，建议保留
	}

	@Override
	public void onApkFileUICheckBoxClick(ApkFileInfo fileInfo) {
		if (fileInfo.getType() == 0 || fileInfo.getType() == 1) {
			for (int i = 0; i < mRecommendClearList.size(); i++) {
				if (fileInfo.getId() == mRecommendClearList.get(i).getId()) {
					mRecommendClearList.get(i).setSelect(fileInfo.getSelect());
					break;
				}
			}
		} else {
			for (int i = 0; i < mRecommendHoldList.size(); i++) {
				if (fileInfo.getId() == mRecommendHoldList.get(i).getId()) {
					mRecommendHoldList.get(i).setSelect(fileInfo.getSelect());
					break;
				}
			}
		}
		setupUI();
		// updateClearButton();
		// mCardsAdapter.notifyDataSetChanged();
	}

	@Override
	public void onApkFileSectionCheckBoxClick(Boolean select, int type) {
		if (type == 0) {
			for (int i = 0; i < mRecommendClearList.size(); i++) {
				mRecommendClearList.get(i).setSelect(select);
			}
		} else if (type == 1) {
			for (int i = 0; i < mRecommendHoldList.size(); i++) {
				mRecommendHoldList.get(i).setSelect(select);
			}
		}
		updateClearButton();
		mCardsAdapter.notifyDataSetChanged();
	}

	private void updateClearButton() {
		int totalCount = 0;
		long totalSize = 0;

		for (int i = 0; i < mRecommendClearList.size(); i++) {
			if (mRecommendClearList.get(i).getSelect()) {
				totalCount++;
				totalSize += mRecommendClearList.get(i).getFileSize();
			}
		}

		for (int j = 0; j < mRecommendHoldList.size(); j++) {
			if (mRecommendHoldList.get(j).getSelect()) {
				totalCount++;
				totalSize += mRecommendHoldList.get(j).getFileSize();
			}
		}
		if (totalCount == 0) {
			mClearBtn.setEnabled(false);
			mClearBtn.setBackgroundResource(R.drawable.download_button_gray);
			mClearBtn.setText("一键清理(" + 0 + "个," + "0M" + ")");
		} else {
			mClearBtn.setEnabled(true);
			mClearBtn.setBackgroundResource(R.drawable.download_button_blue);
			mClearBtn.setText("一键清理(" + totalCount + "个," + Formatter.formatFileSize(this, totalSize) + ")");
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onApkFileUICardClick(final ApkFileInfo fileInfo) {
		if (fileInfo.getType() >= 10) {// 安装
			PackageUtils.launchInstall(this, fileInfo.getFilePath());
			return;
		} // 删除
		if (mDeleteConfimDialog == null) {
			mDeleteConfimDialog = new TextDialog(this);
		}
		mDeleteConfimDialog.showTitle("删除安装包文件").setContent("确定要删除该安装包文件吗？");
		mDeleteConfimDialog.showButton1("关闭", new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mDeleteConfimDialog.cancel();
			}
		});
		mDeleteConfimDialog.showButton2("确定", new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				File file = new File(fileInfo.getFilePath());
				if (file.exists()) {
					boolean ret = file.delete();
					if (ret) {
						mClearFileSize = fileInfo.getFileSize();
						Toast.makeText(getApplicationContext(),
								"删除成功，为您节省 " + Formatter.formatFileSize(getApplicationContext(), mClearFileSize),
								Toast.LENGTH_SHORT).show();

						for (int i = 0; i < mRecommendClearList.size(); i++) {
							if (mRecommendClearList.get(i).getId() == fileInfo.getId()) {
								mRecommendClearList.remove(i);
								setupUI();
								break;
							}
						}
					} else {
						Toast.makeText(getApplicationContext(), "文件" + fileInfo.getFileName() + "删除失败",
								Toast.LENGTH_SHORT).show();
					}
				}
				mDeleteConfimDialog.cancel();
			}
		}).show();
	}
}
